const User = require("../models/user");
const PkManageModule = require('../models/private_key_manage');
const AElfModule = require('../models/aelf')

exports.form = (req, res) => {
    res.render('logout', { title: '登出' });
};

exports.submit = (req, res) => {
    const data = req.body.user;
    User.get_state(data.acct, (state) => {
        if(state.is_online == false){
            console.log("not login!");
            res.redirect('back');
        }
        else{
            const aelf = new AElfModule()
            PkManageModule.get_priKey_by_user(data.acct, (user) => {
                aelf.check_chain_state((state) => {
                    if (state) {
                        aelf.load_wallet(user.priKey, (wallet) => {
                            if(typeof(wallet) !== 'undefined'){
                                aelf.load_contract(true , (param) =>{
                                    console.log("contract prepared");
                                    aelf.logout(param);
                                });
                            }
                        });
                    }
                })

            });
            User.logout(data.acct);
            console.log("logout successful!");
            res.redirect('/');
        }
    })
}